<template>
  <div class="course-list">
    <div class="page-header">
      <h1>课程浏览</h1>
      <p>浏览所有可选课程并进行选课</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" @submit.prevent="handleSearch" inline>
        <el-form-item label="课程名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入课程名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="课程代码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入课程代码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="学分">
          <el-select v-model="searchForm.credit" placeholder="选择学分" clearable style="width: 120px">
            <el-option label="1学分" :value="1" />
            <el-option label="2学分" :value="2" />
            <el-option label="3学分" :value="3" />
            <el-option label="4学分" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="可选" value="available" />
            <el-option label="已满" value="full" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>课程列表</span>
          <div>
            <el-tag>共 {{ total }} 门课程</el-tag>
          </div>
        </div>
      </template>

      <el-table 
        :data="courses" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="课程代码" width="120" />
        <el-table-column prop="name" label="课程名称" min-width="200">
          <template #default="scope">
            <div class="course-info">
              <div class="course-name">{{ scope.row.name }}</div>
              <div class="course-desc" v-if="scope.row.description">
                {{ scope.row.description }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column prop="teacher_name" label="授课教师" width="120" />
        <el-table-column label="选课情况" width="120">
          <template #default="scope">
            <div class="enrollment-info">
              <span>{{ scope.row.current_enrollment || 0 }}/{{ scope.row.capacity }}</span>
              <el-progress 
                :percentage="getEnrollmentPercentage(scope.row)" 
                :stroke-width="4"
                :show-text="false"
                style="margin-top: 4px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row)"
              size="small"
            >
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              v-if="!scope.row.is_selected"
              type="primary"
              size="small"
              @click="handleSelectCourse(scope.row)"
              :disabled="scope.row.current_enrollment >= scope.row.capacity"
            >
              选课
            </el-button>
            <el-button
              v-else
              type="danger"
              size="small"
              @click="handleDropCourse(scope.row)"
            >
              退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedCourses.length > 0">
      <el-card>
        <div class="batch-content">
          <span>已选择 {{ selectedCourses.length }} 门课程</span>
          <div class="batch-buttons">
            <el-button 
              type="primary" 
              @click="handleBatchSelect"
              :disabled="!canBatchSelect"
            >
              批量选课
            </el-button>
            <el-button @click="clearSelection">取消选择</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getAllCourses } from '@/api/course'
import { selectCourse, dropCourse } from '@/api/selection'

const loading = ref(false)
const courses = ref([])
const total = ref(0)
const selectedCourses = ref([])

const searchForm = reactive({
  name: '',
  code: '',
  credit: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  limit: 20
})

// 计算选课进度百分比
const getEnrollmentPercentage = (course) => {
  if (!course.capacity || course.capacity === 0) return 0
  return Math.round((course.current_enrollment || 0) / course.capacity * 100)
}

// 获取状态类型
const getStatusType = (course) => {
  const current = course.current_enrollment || 0
  if (current >= course.capacity) return 'danger'
  if (current / course.capacity > 0.8) return 'warning'
  return 'success'
}

// 获取状态文本
const getStatusText = (course) => {
  const current = course.current_enrollment || 0
  if (current >= course.capacity) return '已满'
  return '可选'
}

// 计算是否可以批量选课
const canBatchSelect = computed(() => {
  return selectedCourses.value.every(course => 
    !course.is_selected && course.current_enrollment < course.capacity
  )
})

// 获取课程列表
const fetchCourses = async () => {
  try {
    loading.value = true
    const params = {
      ...pagination,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getAllCourses(params)
    if (response.code === 0) {
      courses.value = response.data.courses
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 选课操作
const handleSelectCourse = async (course) => {
  if (course.current_enrollment >= course.capacity) {
    ElMessage.warning('该课程已满，无法选课')
    return
  }

  try {
    const response = await selectCourse({ courseId: course.id })
    if (response.code === 0) {
      ElMessage.success('选课成功！')
      course.is_selected = true
      course.current_enrollment = (course.current_enrollment || 0) + 1
    }
  } catch (error) {
    console.error('选课失败:', error)
  }
}

// 退课操作
const handleDropCourse = async (course) => {
  try {
    await ElMessageBox.confirm('确定要退选这门课程吗？', '确认退课', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await dropCourse({ courseId: course.id })
    if (response.code === 0) {
      ElMessage.success('退课成功！')
      course.is_selected = false
      course.current_enrollment = Math.max((course.current_enrollment || 0) - 1, 0)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退课失败:', error)
    }
  }
}

// 批量选课
const handleBatchSelect = async () => {
  const availableCourses = selectedCourses.value.filter(
    course => !course.is_selected && course.current_enrollment < course.capacity
  )

  if (availableCourses.length === 0) {
    ElMessage.warning('没有可选课程')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要选择这 ${availableCourses.length} 门课程吗？`,
      '批量选课确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const promises = availableCourses.map(course => selectCourse({ courseId: course.id }))
    const results = await Promise.allSettled(promises)
    
    let successCount = 0
    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value.code === 0) {
        successCount++
        const course = availableCourses[index]
        course.is_selected = true
        course.current_enrollment = (course.current_enrollment || 0) + 1
      }
    })

    if (successCount > 0) {
      ElMessage.success(`成功选择 ${successCount} 门课程`)
      clearSelection()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量选课失败:', error)
    }
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchCourses()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.page = 1
  fetchCourses()
}

// 分页处理
const handleSizeChange = () => {
  pagination.page = 1
  fetchCourses()
}

const handleCurrentChange = () => {
  fetchCourses()
}

// 表格选择处理
const handleSelectionChange = (selection) => {
  selectedCourses.value = selection
}

const clearSelection = () => {
  selectedCourses.value = []
}

onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.course-list {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info .course-name {
  font-weight: 500;
  color: #303133;
}

.course-info .course-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.enrollment-info {
  font-size: 12px;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.batch-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 16px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-progress-bar__inner) {
  transition: width 0.3s ease;
}
</style> 